/* eslint-disable react/no-array-index-key */
/**
 * 需求简历，详情页
 */
import React from 'react';
import moment from 'moment';
import { Descriptions, Row, Divider, Button, Radio, Icon, Col } from 'antd';
import { history } from 'umi';
import { getDict, getDisplayText } from '@/utils/dataDictUtil';
import AuthComponent from '@/utils/auth/AuthComponent';
import { eventTrack } from '@/utils/track';

import styles from './index.less';
import { ExperienceDescription, ResumeIframe, DetailItem } from '../../components';

import { ABILITY_LEVEL } from '../../dictionary';
import useTalentDetail from '../../useTalentDetail';

function ResumeDetail() {
    const [currTab, setCurrTab] = React.useState('1');
    const talentDetail = useTalentDetail() || {};
    const {
        talentNativePlace,
        talentStandardDetailVO = {},
        talentOriginalDetailVO = {},
        id,
        createTime,
        companyCode,
        origin,
        hasBlackList
    } = talentDetail;

    const { talentOriginalFileUrl = '' } = talentOriginalDetailVO;
    const isNative = /\.pdf(\?.*)?$/.test(talentOriginalFileUrl);

    const previewUrl = isNative
        ? talentOriginalFileUrl
        : `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(talentOriginalFileUrl)}`;
    const [industryTypeList, setIndustryType] = React.useState([]);
    const [agreeTypeList, setAgreeTypeList] = React.useState([]);
    const [recruitTalentLangTypeList, setRecruitTalentLangTypeList] = React.useState([]);
    // 字典获取
    React.useEffect(() => {
        getDict('agreeType').then(ret => setAgreeTypeList(ret));
        getDict('industryType').then(res => setIndustryType(res));
        getDict('recruitTalentLangType').then(res => setRecruitTalentLangTypeList(res));
    }, []);
    const toDetail = () => {
        history.push({
            pathname: '/office/personnelManagement/recruitment/resume/record/edit',
            query: {
                id,
                companyCode,
                origin
            }
        });
    };

    function renderBtns() {
        return (
            <Row>
                { !hasBlackList && <AuthComponent code="office:recruitment:course:resume:edit">
                    <Button
                        size="small"
                        onClick={() => {
                            toDetail();
                            eventTrack({
                                eventName:
                                    'personnel_management_recruitment_demand_list_detail_resume_detail_info_edit_click',
                                pageName: 'personnel_management_recruitment',
                                eventProps: {
                                    click_context: `${talentDetail.dutyName}-${talentDetail.talentName}`
                                }
                            });
                        }}
                    >
                        <Icon type="edit" />
                    </Button>
                </AuthComponent>}
                {talentOriginalFileUrl && (
                    <Button style={{ marginLeft: '12px' }} size="small">
                        <a href={talentOriginalFileUrl}>
                            <Icon type="download" />
                        </a>
                    </Button>
                )}
            </Row>
        );
    }

    const defaultStr = '--';
    const {
        talentIdCard = defaultStr,
        talentWorkDetailVOList = [], // 工作
        talentEduDetailVOList = [], // 教育
        resumeAttachmentList = [], // 附件
        talentProjectDetailVOList = [], // 项目
        talentTrainDetailVOList = [], // 培训
        talentCertificateDetailVOList = [], // 证书
        talentSkillDetailVOList = [], // 技能
        talentLangDetailVOList = [] // 语言能力
    } = talentStandardDetailVO;
    const format = (d, formatStr) => moment(d).format(formatStr);
    const renderTimeRegion = (from, to, formatStr) => {
        if (!from) {
            return '';
        }

        const f = format(from, formatStr);
        const t = to ? format(to, formatStr) : '至今';
        return <span style={{ color: 'rgba(0,0,0,0.45)', fontSize: 12 }}>{`${f} - ${t}`}</span>;
    };

    const renderResume = () => {
        const renderInfo = () => {
            if (!talentIdCard && !talentNativePlace) {
                return '';
            }
            return (
                <>
                    <Descriptions title="个人信息" column={2}>
                        {talentIdCard && <Descriptions.Item label="证件号码">{talentIdCard}</Descriptions.Item>}
                        {talentNativePlace && (
                            <Descriptions.Item label="国籍/户籍">
                                {talentNativePlace?.split(',').join('/')}
                            </Descriptions.Item>
                        )}
                    </Descriptions>
                    <Divider />
                </>
            );
        };
        const renderWork = () => {
            if (!talentWorkDetailVOList.length) {
                return '';
            }
            return (
                <>
                    <Descriptions title="工作经历"></Descriptions>
                    {talentWorkDetailVOList.map((item, index) => (
                        <React.Fragment key={index}>
                            {index !== 0 && <div style={{ marginTop: 40 }}></div>}
                            <ExperienceDescription
                                showAvatar={false}
                                major={[item.companyName, renderTimeRegion(item.startTime, item.endTime, 'YYYY.MM')]}
                                secondary={[
                                    item.positionName,
                                    item.industryType
                                        ? `所属行业：${getDisplayText(industryTypeList, item.industryType)}`
                                        : ''
                                ]}
                                extra={item.leaveReason && <div>离职原因：{item.leaveReason}</div>}
                                description={[{ content: item.workDesc && item.workDesc.split('\n') }]}
                            />
                        </React.Fragment>
                    ))}
                    <Divider />
                </>
            );
        };
        const renderProject = () => {
            if (!talentProjectDetailVOList.length) {
                return '';
            }
            return (
                <>
                    <Descriptions title="项目经验"></Descriptions>
                    {talentProjectDetailVOList.map((item, index) => (
                        <React.Fragment key={index}>
                            {index !== 0 && <div style={{ marginTop: 40 }}></div>}
                            <ExperienceDescription
                                showAvatar={false}
                                major={[item.projectName, renderTimeRegion(item.startTime, item.endTime, 'YYYY.MM')]}
                                description={[
                                    { title: '项目描述', content: item.projectDesc && item.projectDesc.split('\n') },
                                    {
                                        title: '项目中职责',
                                        content: item.projectWorkDesc && item.projectWorkDesc.split('\n')
                                    }
                                ]}
                            />
                        </React.Fragment>
                    ))}
                    <Divider />
                </>
            );
        };
        const renderEdu = () => {
            if (!talentEduDetailVOList.length) {
                return '';
            }
            const fetchSecondary = (degree, major) => [degree, major].filter(_ => _).join(' / ');
            return (
                <>
                    <Descriptions title="教育背景"></Descriptions>
                    {talentEduDetailVOList.map((item, index) => (
                        <React.Fragment key={index}>
                            {index !== 0 && <div style={{ marginTop: 40 }}></div>}
                            <ExperienceDescription
                                icon={
                                    <i
                                        className="icon iconfont iconlist_school_icon_default1"
                                        style={{ fontSize: '32px' }}
                                    ></i>
                                }
                                avatar={item.avatar}
                                major={[item.graduateSchool, renderTimeRegion(item.startTime, item.endTime, 'YYYY')]}
                                secondary={[fetchSecondary(getDisplayText(agreeTypeList, item.degree), item.major)]}
                            />
                        </React.Fragment>
                    ))}
                    <Divider />
                </>
            );
        };
        const renderTrain = () => {
            if (!talentTrainDetailVOList.length) {
                return '';
            }
            return (
                <>
                    <Descriptions title="培训经历"></Descriptions>
                    {talentTrainDetailVOList.map((item, index) => (
                        <React.Fragment key={index}>
                            {index !== 0 && <div style={{ marginTop: 40 }}></div>}
                            <ExperienceDescription
                                showAvatar={false}
                                major={[item.trainOrganize, renderTimeRegion(item.startTime, item.endTime, 'YYYY')]}
                                description={[{ content: item.trainContent && item.trainContent.split('\n') }]}
                            />
                        </React.Fragment>
                    ))}
                    <Divider />
                </>
            );
        };
        const renderCertificate = () => {
            if (!talentCertificateDetailVOList.length) {
                return '';
            }
            return (
                <>
                    <Descriptions title="获得证书"></Descriptions>
                    {talentCertificateDetailVOList.map((item, index) => (
                        <React.Fragment key={index}>
                            {index !== 0 && <div style={{ marginTop: 40 }}></div>}
                            <ExperienceDescription
                                showAvatar={false}
                                major={[item.certificateName, format(item.certificateTime, 'YYYY.MM')]}
                            />
                        </React.Fragment>
                    ))}
                    <Divider />
                </>
            );
        };
        const renderSkill = () => {
            if (!talentSkillDetailVOList.length) {
                return '';
            }
            return (
                <>
                    <Descriptions title="专业技能"></Descriptions>
                    {talentSkillDetailVOList
                        .filter(item => item.skillName)
                        .map((item, index) => (
                            <div key={index}>
                                {index !== 0 && <div style={{ marginTop: 10 }}></div>}
                                <Row style={{ marginLeft: 12 }}>
                                    <Col span={8}>
                                        <DetailItem>{item.skillName}</DetailItem>
                                    </Col>
                                    <Col span={8}>
                                        <DetailItem label="掌握程度" style={{ flex: 1 }}>
                                            {getDisplayText(ABILITY_LEVEL, item.proficiency) || '-'}
                                        </DetailItem>
                                    </Col>
                                    <Col span={8}>
                                        <DetailItem label="使用时长">
                                            {item.skillDuration ? `${item.skillDuration}月` : '-'}
                                        </DetailItem>
                                    </Col>
                                </Row>
                            </div>
                        ))}
                    <Divider />
                </>
            );
        };
        const renderLang = () => {
            if (!talentLangDetailVOList.length) {
                return '';
            }
            return (
                <>
                    <Descriptions title="语言能力"></Descriptions>
                    {talentLangDetailVOList
                        .filter(item => item.langType)
                        .map((item, index) => (
                            <div key={index}>
                                {index !== 0 && <div style={{ marginTop: 10 }}></div>}
                                <Row key={index} style={{ marginLeft: 12 }}>
                                    <Col span={8}>
                                        <DetailItem>
                                            {getDisplayText(recruitTalentLangTypeList, item.langType)}
                                        </DetailItem>
                                    </Col>
                                    <Col span={8}>
                                        <DetailItem label="听说能力" style={{ flex: 1 }}>
                                            {getDisplayText(ABILITY_LEVEL, item.listenSpeakAbility) || '-'}
                                        </DetailItem>
                                    </Col>
                                    <Col span={8}>
                                        <DetailItem label="读写能力">
                                            {getDisplayText(ABILITY_LEVEL, item.readWriteAbility) || '-'}
                                        </DetailItem>
                                    </Col>
                                </Row>
                            </div>
                        ))}

                    <Divider />
                </>
            );
        };
        const renderAttachment = () => {
            if (!resumeAttachmentList.length) {
                return '';
            }
            return (
                <>
                    <Descriptions title="附件"></Descriptions>
                    <Row>
                        {resumeAttachmentList.map((item, index) => {
                            const { originName, url } = item;
                            return (
                                <div key={index}>
                                    {index !== 0 && <div style={{ marginTop: 10 }}></div>}
                                    <Row type="flex" align="middle">
                                        <Col>
                                            <i
                                                className="icon iconfont iconyuanshijianli"
                                                style={{ color: 'rgba(0, 0, 0, 0.25)', fontSize: '16px' }}
                                            ></i>
                                        </Col>
                                        <a
                                            rel="noopener noreferrer"
                                            href={url}
                                            download
                                            style={{
                                                marginLeft: '12px',
                                                cursor: 'pointer',
                                                color: 'rgba(0, 0, 0, 0.85)'
                                            }}
                                        >
                                            <span>{originName}</span>
                                        </a>
                                    </Row>
                                </div>
                            );
                        })}
                    </Row>
                    <Divider />
                </>
            );
        };
        return (
            <Row className={styles.resumeDetailWrapper}>
                {renderInfo()}
                {renderWork()}
                {renderProject()}
                {renderEdu()}
                {renderTrain()}
                {renderCertificate()}
                {renderLang()}
                {renderSkill()}
                {renderAttachment()}
                <Descriptions title="入库情况" column={2}>
                    <Descriptions.Item label="入库时间">{format(createTime, 'YYYY-MM-DD HH:mm')}</Descriptions.Item>
                    {/* <Descriptions.Item label="负责人">
                        {talentNativePlace ? talentNativePlace?.split(',').join('/') : ''}
                    </Descriptions.Item> */}
                </Descriptions>
            </Row>
        );
    };
    return (
        <>
            <Row type="flex" justify="space-between" style={{ marginBottom: 24 }}>
                <Radio.Group size="middle" defaultValue={currTab} onChange={e => setCurrTab(e.target.value)}>
                    <Radio.Button
                        value="1"
                        onClick={() => {
                            eventTrack({
                                eventName:
                                    'personnel_management_recruitment_demand_list_detail_resume_detail_info_standard_click',
                                pageName: 'personnel_management_recruitment',
                                eventProps: {
                                    click_context: `${talentDetail.dutyName}-${talentDetail.talentName}`
                                }
                            });
                        }}
                    >
                        <i className="icon iconfont iconbiaozhunjianli" style={{ marginRight: 4 }}></i>
                        标准简历
                    </Radio.Button>
                    <Radio.Button
                        value="2"
                        onClick={() => {
                            eventTrack({
                                eventName:
                                    'personnel_management_recruitment_demand_list_detail_resume_detail_info_original_click',
                                pageName: 'personnel_management_recruitment',
                                eventProps: {
                                    click_context: `${talentDetail.dutyName}-${talentDetail.talentName}`
                                }
                            });
                        }}
                    >
                        <i className="icon iconfont iconyuanshijianli" style={{ marginRight: 4 }}></i>
                        原始简历
                    </Radio.Button>
                </Radio.Group>
                {renderBtns()}
            </Row>
            {currTab === '1' && renderResume()}
            {currTab === '2' && talentOriginalFileUrl && <ResumeIframe url={previewUrl} isNative={isNative} />}
        </>
    );
}
export default ResumeDetail;
